#include "add_friend_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <algorithm>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/regex.hpp>
#include <boost/tokenizer.hpp>
#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"

namespace imserver {
namespace fcgi {

bool AddFriendRequest::Response() {
  LOG_DEBUG("AddFriendRequest::Response called." << body_);
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  // 解析请求的数据，得到当前用户的id、http表单提交的用户ID和回调接口。
  ParseUserIdentity();
  std::string callback = GetPostArg("callback");
  int64_t qid = GetPostArgInt("qid");

  std::string rsp_header("Content-type: text/html; charset=utf-8\r\n\r\n");
  FCGX_PutS(rsp_header.c_str(), fcgi_out_);

  // 判断得到的数据是合法化，如果全合法则通知联系人服务去增加这一好友关系
  if (effective_id() > 0 && qid > 0 && !callback.empty()) {
    LOG_INFO("[AddFriendRequest::Response] Local user " << effective_id() << " add friend " << qid);
    RecentContactAdapter::Instance().AddFavorite(effective_id(), qid, 2);
    std::string rsp_body = boost::str(boost::format("<script>document.domain=\"360.cn\"; %1%({errno:%2%})</script>") % callback % 0);
    FCGX_PutS(rsp_body.c_str(), fcgi_out_);
  } else {
    LOG_ERROR("[AddFriendRequest::Response] Local user " << effective_id()
        << " add friend " << qid << " with callback(" << callback << ") error.");
    std::string rsp_body("{errno:-1}");
    FCGX_PutS(rsp_body.c_str(), fcgi_out_);
  }

  return true;
}

}
}


